<?php


namespace App\Modules\Health\Services;


use App\Modules\Health\Models\HealthConfigs;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;

class ConfigService
{
    const CACHE_TAG = 'health_configs';

    public function getConfigs(string $group, ?string $name = null)
    {
        $key = "health-{$group}";

        $data = Cache::tags(self::CACHE_TAG)->get($key);

        if (!$data) {
            $data = HealthConfigs::where('group', $group)->pluck('value', 'name')->all();
            if (!$data) {
                return null;
            }

            Cache::tags(self::CACHE_TAG)->put($key, $data, 3600);
        }

        return is_null($name) ? $data : Arr::get($data, $name);
    }

    public function flushConfigs(?string $group = null)
    {
        if (is_null($group)) {
            Cache::tags(self::CACHE_TAG)->flush();
        } else {
            Cache::tags(self::CACHE_TAG)->forget("health-{$group}");
        }
    }
}
